from fastapi import HTTPException, status
from sqlalchemy.exc import SQLAlchemyError

from handle.handle_log import log
from server.controller.log import create_log
from server.db.models.system import Role


def role_add(request, role, db, current_user):
    """
    添加权限
    :param request:
    :param role:
    :param current_user:
    :param db:
    :return:
    """

    # 检查用户是否存在
    existing_user = db.query(Role).filter(
        Role.name == role.name,
        Role.is_deleted == False
    ).first()
    if existing_user:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            params=str(role),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=1400,
            response="权限已存在"
        )
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail={"code": 1400, "msg": "权限已存在"}
        )
    try:
        new_role = Role(
            name=role.name,
            code=role.code,
            description=role.description,
            is_active=role.is_active,
            is_deleted=role.is_deleted,
        )
        db.add(new_role)
        db.commit()
        db.refresh(new_role)
    except SQLAlchemyError as e:
        log.error(f": {e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )

    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            user_agent=request.headers.get('User-Agent'),
            status_code=200,
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}


def get_role_list(request, db, current_user):
    """
    获取权限列表
    :param request:
    :param current_user:
    :param db:
    :return:
    """

    try:
        db_role = db.query(Role).all()
    except SQLAlchemyError as e:
        log.error(f": {e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        role_list = []
        for role in db_role:
            role_list.append(
                {
                    "name": role.name,
                    "code": role.code,
                    "description": role.description,
                    "is_active": role.is_active,
                    "created_at": role.created_at,
                    "updated_at": role.updated_at
                }
            )
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"data": role_list,"code": 200, "msg": "操作成功"}


def role_update(request, role, db, current_user):
    """
    更新权限
    :param role:
    :param current_user:
    :param request:
    :param db:
    :return:
    """

    try:
        db.query(Role).filter(Role.id == role.id).update(
            {
                Role.name: role.name,
                Role.code: role.code,
                Role.description: role.description,
                Role.is_active: role.is_active
            }
        )
        db.commit()
    except SQLAlchemyError as e:
        log.error(f": {e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=1500,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}


def role_delete(request, delete_role, db, current_user):
    """
    删除权限
    :param request:
    :param delete_perm:
    :param db:
    :return:
    """

    try:
        db.query(Role).filter(Role.id == delete_role.id).update(
            {Role.is_deleted: True}
        )
        db.commit()
    except SQLAlchemyError as e:
        log.error(f": {e}")
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="系统错误"
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"code": 1500, "msg": "系统错误"}
        )
    else:
        create_log(
            db=db,
            user_id=current_user,
            method=request.method,
            path=str(request.url),
            ip_address=request.client.host,
            status_code=200,
            user_agent=request.headers.get("User-Agent"),
            response="操作成功"
        )
        return {"code": 200, "msg": "操作成功"}
